package com.cn.wanxi.servlet.back.company;

import com.cn.wanxi.model.CompanyModel;
import com.cn.wanxi.model.ResultModel;
import com.cn.wanxi.service.ICompanyService;
import com.cn.wanxi.service.impl.CompanyServiceImpl;
import net.sf.json.JSONArray;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@WebServlet("/companyUpdate")
public class CompanyUpdateServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //得到上传文件的保存目录，将上传的文件存放在WEB-INF目录下面 不允许外界直接访问，保证上传文件的安全性
        /*        String savePath  = this.getServletContext().getRealPath("/WEB-INF/upload");*/
        String path = "\\LoadJsp\\";
        String savePath = "E:\\wanxi\\step-four\\canyin04-0526\\web" + path;
        File file = new File(savePath);
        if (!file.exists() && !file.isDirectory()) {
            System.out.println(savePath + "目标目录不存在，需要进行创建");
            file.mkdir();
        }
        String message = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //1 创建DiskFileItemFactory工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //2 创建一个文件上传解析器
            ServletFileUpload upload = new ServletFileUpload(factory);
            //判断提交上来的数据是不是表单上的数据
            upload.setHeaderEncoding("UTF-8");
            if (!ServletFileUpload.isMultipartContent(req)) {
                return;
            }
            //4 使用ServletFileUpload解析器来解析上传数据，解析结果返回的是一个List<FileItem>
            //集合，每一个FileItem对应一个Form表单的输入项
            List<FileItem> list = upload.parseRequest(req);
            for (FileItem item : list) {
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString("UTF-8");
                    System.out.println(name + "=" + value);
                    stringBuilder.append(value + "@&@");
                } else {
                    String filename = item.getName();
                    System.out.println(filename);
                    if (filename == null || filename.trim().equals("")) {
                        continue;//跳出当前循环
//                        break;//跳出所有
//                        return;跳出方法
                    }
                    //注意：不同的浏览器提交的文件名是不一样的，有些浏览器提交上来的文件名是带有路径的，如：  c:\a\b\1.txt，而有些只是单纯的文件名，如：1.txt
                    //处理获取到的上传文件的文件名的路径部分，只保留文件名部分
                    filename = filename.substring(filename.lastIndexOf("\\") + 1);
                    //获取item输入流
                    InputStream inputStream = item.getInputStream();
                    //创建一个文件输出流
                    String imgurl = path + filename;//保存到数据库的位置
                    String url = savePath + filename;//保存到服务器的路径
                    stringBuilder.append(imgurl + "@&@");//需要得到数据库的路径
                    FileOutputStream fileOutputStream = new FileOutputStream(url);
                    //创建一个缓冲区
                    byte buffer[] = new byte[1024];
                    //判断输入流是否已经读完的标识
                    int len = 0;
                    while ((len = inputStream.read(buffer)) > 0) {
                        fileOutputStream.write(buffer, 0, len);
                    }
                    inputStream.close();
                    fileOutputStream.close();
                    item.delete();
                    message = "文件上传成功";
                }
            }
        } catch (Exception e) {
            message = "文件上传失败";
            e.printStackTrace();
        }
        System.out.println(stringBuilder);
        String[] ss = stringBuilder.toString().split("@&@");

        CompanyModel companyModel = new CompanyModel();
        Integer id = "".equals(ss[0]) ? 0 : Integer.parseInt(ss[0]);
        companyModel.setId(id);
        companyModel.setName(ss[1]);
        companyModel.setLogo(ss[2].replace("\\", "/"));
        companyModel.setPhone(ss[3]);
        companyModel.setCompanyIntroduce(ss[4]);
        ICompanyService iCompanyService = new CompanyServiceImpl();
        ResultModel resultModel = null;
        if (id == 0) {
            resultModel = iCompanyService.add(companyModel);
        } else {
            resultModel = iCompanyService.update(companyModel);
        }

        JSONArray jsonArray = JSONArray.fromObject(resultModel);
        resp.getWriter().println(jsonArray);


    }
}
